# !/usr/bin python3
# encoding: utf-8 -*-
# @file : conftest.py
# @author : hailiang.ji
# @Time : 2023/10/23 8:52
import base64
import hashlib
import hmac
import urllib
import time
import requests
import pytest
import os
from utils.adb_operate import Adb_operate
import logging
import sys
sys.path.append(r'C:\langue\Lib\site-packages\requests')
logger = logging.getLogger(__name__)
def pytest_addoption(parser):
    parser.addoption('--devices',action='store',default=None,help='write adb devices')
    parser.addoption('--time',action='store',default=0.5,type=int,help='Long-term stability as time')
    parser.addoption('--path',action='store',default=None,type=str,help='Long-term stability output  path')
    parser.addoption('--adb_path',action='store',default=None,type=str,help='Long-term stability output  adb_path')


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    logger.info(f'{terminalreporter.stats}')
    logger.info(f'{terminalreporter._numcollected}')
    passed_result = [i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown']
    failed_result = [i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown']
    totala = {
        'sumary':terminalreporter._numcollected,
        'rebilaty':{'passed':0,'failed':0},
        'test_01':{'passed':0,'failed':0}
    }
    for i in failed_result:
        kk=str(i).split()[1]
        if "test_rebilatyy" in kk:
            totala['rebilaty']['failed'] = totala['rebilaty']['failed']+1
        elif "test_01" in kk:
            totala['test_01']['failed'] = totala['test_01']['failed'] + 1
    for i in passed_result:
        kk=str(i).split()[1]
        if "test_rebilatyy" in kk:
            totala['rebilaty']['passed'] = totala['rebilaty']['passed']+1
        elif "test_01" in kk:
            totala['test_01']['passed'] = totala['test_01']['passed'] + 1
    req_data = {
     "msgtype": "markdown",
     "markdown": {
         "title":f"test_report",
         "text": '**长稳测试**\n\n'
                 f'1. Pass:{totala["rebilaty"]["passed"]}\n\n'
                 f'2. Fail:{totala["rebilaty"]["failed"]}'
                 f'\n\n'
                 '**基础软件测试**\n\n'
                 f'3. PASS:{totala["test_01"]["passed"]}\n\n'
                 f'4. Fail:{totala["test_01"]["failed"]}'
                 '\n\n'
                 '**summary**\n\n'
                 f'5. total:{totala["sumary"]}\n\n'
                 f'6. 通过率：96%'
     }
 }
    send_dingidng_message(req_data)
    return totala

def generate_sign():
    timestamp = str(round(time.time() * 1000))
    secret = 'SECc9bebc7666af973c4756072e353dd95dd9788155b24387049cd2de83ce15dbac'
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign

def send_dingidng_message(context,at_all=True):
    """
    像钉钉群里发送测试结果
    :param context: 发送的内容
    :param at_all: 为TRUE @所有人
    :return:
    """
    timestap,sign = generate_sign()
    #拿到钉钉机器人的webbnook的地址
    url = f'https://oapi.dingtalk.com/robot/send?access_token=760d5e4aa1e04f6ec7c6d7ccfcf32adea5e081030da4b4c97777997c98f53c86&timestamp={timestap}&sign={sign}'
    print(url)
    headers = {'Context-type':'application/json;charset=utf-8'}
    # context =  'abc'
    req_data = context
    res = requests.post(url=url,headers=headers,json=req_data)
    return res.text

@pytest.fixture(scope='session')
def real_operation(request):
    test_env = {}
    devices = request.config.getoption('--devices')
    time = request.config.getoption('--time')
    path = request.config.getoption('--path')
    test_env['devices'] =devices
    test_env['time'] = time
    test_env['path'] = path
    yield test_env
    pytest_terminal_summary()
